package com.canto.access.pojo.bo;

import com.canto.wanna.user.pojo.doo.ResourceDO;
import com.canto.wanna.user.pojo.doo.UserDO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 权限管理用户详情信息
 *
 * @author jsryin
 * @version 2021-07-06
 */
public class AccessUserDetails implements UserDetails {

    /**
     * 用户基础信息
     */
    private UserDO userDO;

    /**
     * 模块资源表
     */
    private List<ResourceDO> resourceDOList;

    public AccessUserDetails(UserDO userDO, List<ResourceDO> resourceDOList) {
        this.userDO = userDO;
        this.resourceDOList = resourceDOList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Optional.ofNullable(resourceDOList).orElseGet(() -> new ArrayList<>())
                .parallelStream()
                .map(resourceDO -> new SimpleGrantedAuthority(resourceDO.getAuthority()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return userDO.getPassword();
    }

    @Override
    public String getUsername() {
        return userDO.getName();
    }

    /**
     * 账号是否过期
     *
     * @return true=未过期；false=已过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 用户账号是否被锁定
     *
     * @return true=未锁定；false=锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 用户账号凭证（密码）是否过期
     * 简单的说就是可能会因为修改了密码导致凭证过期这样的场景
     *
     * @return true=过期；false=未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户账号是否被启用
     *
     * @return true=启用；false=禁用
     */
    @Override
    public boolean isEnabled() {
        return "1".equals(userDO.getStatus());
    }
}
